﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarCrash.Core.Model;
using CarCrash.Core.helper;
using NHibernate;
using NHibernate.Criterion;

namespace CarCrash.Core.Services
{
    /* 
     * Синглтон, сервис для доступа к транспортным средствам.
     */
    public class VehicleService : GenericDaoService<Vehicle>
    {

        public Vehicle GetByModel(string brand, string model) {
            ISession session = NHibernateHelper.GetCurrentSession();
            return session.CreateCriteria<Vehicle>()
                .Add(Restrictions.Eq("Brand", brand))
                .Add(Restrictions.Eq("Model", model))
                .UniqueResult<Vehicle>();
        }

        public IList<Vehicle> GetAllByBrand(string brand)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            return session.CreateCriteria<Vehicle>()
                .Add(Restrictions.Eq("Brand", brand))
                .List<Vehicle>();
        }

        public void SaveOrUpdate(VehicleParameters param)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.SaveOrUpdate(param);
                transaction.Commit();
            }
        }

        public IList<string> GetBrands()
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            ICriteria c = session.CreateCriteria(typeof(Vehicle));
            c.SetProjection(Projections.Distinct(Projections.ProjectionList().Add(Projections.Property("Brand"))));
            return c.List<string>();
        }

        // данная реализация не предназначена для многопоточности!
        private static VehicleService instance;
        private VehicleService() { }
        public static VehicleService Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new VehicleService();
                }
                return instance;
            }
        }

    }
}